package net.fruit.mq.client.impl.tracehook;

import java.util.ArrayList;
import java.util.List;

import org.apache.rocketmq.client.consumer.listener.ConsumeReturnType;
import org.apache.rocketmq.client.hook.ConsumeMessageContext;
import org.apache.rocketmq.client.hook.ConsumeMessageHook;
import org.apache.rocketmq.common.MixAll;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.common.message.MessageExt;

import net.fruit.mq.client.trace.common.MQTraceBean;
import net.fruit.mq.client.trace.common.MQTraceConstants;
import net.fruit.mq.client.trace.common.MQTraceContext;
import net.fruit.mq.client.trace.common.MQTraceType;
import net.fruit.mq.client.trace.dispatch.AsyncDispatcher;

public class MQConsumeMessageHookImpl implements ConsumeMessageHook {
    /**
     * 该Hook该由哪个dispatcher发送轨迹数据
     */
    private AsyncDispatcher localDispatcher;


    public MQConsumeMessageHookImpl(AsyncDispatcher localDispatcher) {
        this.localDispatcher = localDispatcher;
    }


    @Override
    public String hookName() {
        return "MQConsumeMessageHook";
    }


    @Override
    public void consumeMessageBefore(ConsumeMessageContext context) {
        if (context == null || context.getMsgList() == null || context.getMsgList().isEmpty()) {
            return;
        }
        MQTraceContext mqTraceContext = new MQTraceContext();
        context.setMqTraceContext(mqTraceContext);
        mqTraceContext.setTraceType(MQTraceType.SubBefore);//
        mqTraceContext.setGroupName(context.getConsumerGroup());//
        List<MQTraceBean> beans = new ArrayList<MQTraceBean>();
        for (MessageExt msg : context.getMsgList()) {
            if (msg == null) {
                continue;
            }
            String regionId =msg.getProperty(MessageConst.PROPERTY_MSG_REGION);
            String traceOn = msg.getProperty(MessageConst.PROPERTY_TRACE_SWITCH);
            if(regionId ==null || regionId.equals(MQTraceConstants.default_region)){
                // if regionId is default ,skip it
                continue;
            }
            if(traceOn!=null && traceOn.equals("false")){
                // if trace switch is false ,skip it
                continue;
            }
            MQTraceBean traceBean = new MQTraceBean();
            traceBean.setTopic(msg.getTopic());//
            traceBean.setMsgId(msg.getMsgId());//
            traceBean.setTags(msg.getTags());//
            traceBean.setKeys(msg.getKeys());//
            traceBean.setStoreTime(msg.getStoreTimestamp());//
            traceBean.setBodyLength(msg.getStoreSize());//
            traceBean.setRetryTimes(msg.getReconsumeTimes());//
            mqTraceContext.setRegionId(regionId);//
            beans.add(traceBean);
        }
        if(beans.size()>0){
            mqTraceContext.setTraceBeans(beans);
            mqTraceContext.setTimeStamp(System.currentTimeMillis());
            localDispatcher.append(mqTraceContext);
        }
    }


    @Override
    public void consumeMessageAfter(ConsumeMessageContext context) {
        if (context == null || context.getMsgList() == null || context.getMsgList().isEmpty()) {
            return;
        }
        MQTraceContext subBeforeContext = (MQTraceContext) context.getMqTraceContext();
        if(subBeforeContext.getRegionId().equals(MQTraceConstants.default_region)){
            // if regionId is default ,skip it
            return;
        }
        if(subBeforeContext.getTraceBeans()==null || subBeforeContext.getTraceBeans().size()<1){
            // if subbefore bean is null ,skip it
            return;
        }
        MQTraceContext subAfterContext = new MQTraceContext();
        subAfterContext.setTraceType(MQTraceType.SubAfter);//
        subAfterContext.setRegionId(subBeforeContext.getRegionId());//
        subAfterContext.setGroupName(subBeforeContext.getGroupName());//
        subAfterContext.setRequestId(subBeforeContext.getRequestId());//
        subAfterContext.setSuccess(context.isSuccess());//
        // 批量消息全部处理完毕的平均耗时
        int costTime = (int) ((System.currentTimeMillis() - subBeforeContext.getTimeStamp()) / context.getMsgList().size());
        subAfterContext.setCostTime(costTime);//
        subAfterContext.setTraceBeans(subBeforeContext.getTraceBeans());
        String contextType =context.getProps().get(MixAll.CONSUME_CONTEXT_TYPE);
        if(contextType!=null){
            subAfterContext.setContextCode(ConsumeReturnType.valueOf(contextType).ordinal());
        }
        localDispatcher.append(subAfterContext);
    }
}
